package org.baicaixiaozhan.tenet.reflection.aop.interceptor;

import org.baicaixiaozhan.tenet.reflection.aop.Advice;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * DESC: 通过 {@link InvocationHandler} 接口简单实现 JDK 版的 MethodInterceptor
 *
 * @author baicaixiaozhan
 * @since 1.0.0
 */
public class SimpleJdkInterceptor implements InvocationHandler, Serializable {

    private final Object target;
    private final Advice advice;

    public SimpleJdkInterceptor(Object target, Advice advice) {
        this.target = target;
        this.advice = advice;
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        final Object target = this.target;
        final Advice advice = this.advice;
        Object result = null;

        if (advice.interrupt(target, method, args)) {
            return null;
        }
        advice.before(target, method, args);
        if (Modifier.isPrivate(method.getModifiers())) {
            method.setAccessible(true);
        }
        try {
            result = method.invoke(target, args);
            advice.afterReturning(result, target, method, args);
        } catch (Throwable t) {
            advice.afterThrowing(target, method, args, t);
            throw t;
        } finally {
            advice.after(target,method, args);
        }
        return result;
    }



}
